
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: CursorStateTest4.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar.util;

import com.sleepycat.je.DatabaseEntry;

import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

public class CursorStateTest4 extends CursorStateTest {

    @Test(dependsOnMethods = { "iterateForward", "iterateBackward", "iterateRandomly", "iterateSecondary" })
    public void checkDelete() {

        // Pick a random value in the database
        final BDB bdb = getBDB();

        // Check seeking to it
        CloseableNotes.performAction(new VoidDatabaseAction() {
            public void executeVoid() {
                CursorState cursorState = new CursorState(bdb.db.openCursor(env.getCurrentTransaction(), null));

                // 0th entry
                boolean found = cursorState.forward();
                assertTrue(found);
                assertEquals(cursorState.getCurrentKey(), getEntry(0));
                assertEquals(cursorState.getCurrentData(), getEntry(0));

                // 1st entry
                found = cursorState.forward();
                assertTrue(found);
                assertTrue(cursorState.isActive());
                assertEquals(cursorState.getCurrentKey(), getEntry(1));
                assertEquals(cursorState.getCurrentData(), getEntry(-1));

                // Delete it
                cursorState.delete();
                assertTrue(cursorState.isActive());

                // 0th entry again
                found = cursorState.backward();
                assertTrue(found);
                assertEquals(cursorState.getCurrentKey(), getEntry(0));
                assertEquals(cursorState.getCurrentData(), getEntry(0));

                // 2nd entry
                found = cursorState.forward();
                assertTrue(found);
                assertTrue(cursorState.isActive());
                assertEquals(cursorState.getCurrentKey(), getEntry(2));
                assertEquals(cursorState.getCurrentData(), getEntry(-2));
            }
        });
    }

    @Override
    protected int getNumEntries(String name) {
        return 3;
    }

    @Override
    protected void createEntry(String name, int i, DatabaseEntry key, DatabaseEntry value) {
        getEntry(key, i);
        getEntry(value, -i);
    }

    private void getEntry(DatabaseEntry entry, int i) {
        entry.setData(new byte[] { (byte)i });
    }

    private DatabaseEntry getEntry(int i) {
        DatabaseEntry entry = new DatabaseEntry();
        getEntry(entry, i);
        return entry;
    }
}

